from PyQt6.QtWidgets import QWidget
from PyQt6.QtCore import Qt, QTimer, QRectF
from PyQt6.QtGui import (
    QPainter, QColor, QRadialGradient, QFont, QPainterPath,
    QPen, QLinearGradient
)
import math


class EnergyBallWidget(QWidget):
    def __init__(self, percent=50, parent=None):
        super().__init__(parent)
        self.target_percent = percent       # 目标液量
        self.current_percent = percent      # 当前液量（用于动画过渡）
        self.setFixedSize(120, 120)
        self.phase = 0
        self.glow_alpha = 180
        self.glow_direction = 1

        # === 动画定时器 ===
        self.wave_timer = QTimer(self)
        self.wave_timer.timeout.connect(self._update_wave)
        self.wave_timer.start(40)

        # 液面平滑变化定时器
        self.percent_timer = QTimer(self)
        self.percent_timer.timeout.connect(self._update_percent)
        self.percent_timer.start(30)

        # 呼吸光环
        self.glow_timer = QTimer(self)
        self.glow_timer.timeout.connect(self._update_glow)
        self.glow_timer.start(80)

    # ---------------- 动画更新 ---------------- #
    def _update_wave(self):
        self.phase += 0.25
        if self.phase >= 2 * math.pi:
            self.phase = 0
        self.update()

    def _update_glow(self):
        self.glow_alpha += self.glow_direction * 6
        if self.glow_alpha >= 220:
            self.glow_direction = -1
        elif self.glow_alpha <= 100:
            self.glow_direction = 1
        self.update()

    def _update_percent(self):
        """液面平滑过渡动画"""
        diff = self.target_percent - self.current_percent
        if abs(diff) < 0.2:  # 接近目标
            self.current_percent = self.target_percent
        else:
            self.current_percent += diff * 0.05  # 逐步逼近
        self.update()

    # ---------------- 绘制 ---------------- #
    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        w, h = self.width(), self.height()
        r = min(w, h) / 2 - 5
        cx, cy = w / 2, h / 2

        # === 背景 ===
        bg_grad = QRadialGradient(cx, cy, r)
        bg_grad.setColorAt(0.0, QColor(0, 80, 150, 255))
        bg_grad.setColorAt(1.0, QColor(0, 30, 60, 255))
        painter.setPen(Qt.PenStyle.NoPen)
        painter.setBrush(bg_grad)
        painter.drawEllipse(QRectF(cx - r, cy - r, 2 * r, 2 * r))

        # === 液体颜色 ===
        percent = self.current_percent
        if percent > 60:
            top_color = QColor(0, 255, 255, 180)
            bottom_color = QColor(0, 180, 255, 200)
        elif percent > 30:
            top_color = QColor(255, 220, 0, 200)
            bottom_color = QColor(255, 150, 0, 220)
        else:
            top_color = QColor(255, 80, 0, 220)
            bottom_color = QColor(150, 0, 0, 240)

        # === 波浪路径 ===
        wave_path = QPainterPath()
        wave_top = h * (1 - percent / 100.0)
        amplitude = 6
        wavelength = w / 1.2
        wave_path.moveTo(0, h)
        for x in range(0, w + 1, 2):
            y = wave_top + amplitude * math.sin(2 * math.pi * x / wavelength + self.phase)
            wave_path.lineTo(x, y)
        wave_path.lineTo(w, h)
        wave_path.closeSubpath()

        # === 液体渐变 + 圆形裁剪 ===
        painter.save()
        clip_path = QPainterPath()
        clip_path.addEllipse(QRectF(cx - r, cy - r, 2 * r, 2 * r))
        painter.setClipPath(clip_path)

        liquid_grad = QLinearGradient(0, wave_top - 20, 0, h)
        liquid_grad.setColorAt(0.0, top_color)
        liquid_grad.setColorAt(1.0, bottom_color)
        painter.setPen(Qt.PenStyle.NoPen)
        painter.setBrush(liquid_grad)
        painter.drawRect(QRectF(0, wave_top, w, h - wave_top))

        # 半透明波浪层
        painter.setBrush(QColor(255, 255, 255, 60))
        painter.drawPath(wave_path)
        painter.restore()

        # === 外圈发光 ===
        pen = QPen(QColor(0, 255, 255, self.glow_alpha), 3)
        painter.setPen(pen)
        painter.setBrush(Qt.BrushStyle.NoBrush)
        painter.drawEllipse(QRectF(cx - r, cy - r, 2 * r, 2 * r))

        # === 百分比文字 ===
        painter.setFont(QFont("Arial", 14, QFont.Weight.Bold))
        text = f"{percent:.0f}%"
        pen = QPen(QColor(0, 0, 0, 200), 2)
        painter.setPen(pen)
        painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, text)
        painter.setPen(Qt.GlobalColor.white)
        painter.drawText(self.rect(), Qt.AlignmentFlag.AlignCenter, text)

    # ---------------- 外部接口 ---------------- #
    def setPercent(self, value: float):
        """设置目标液量（自动平滑过渡）"""
        self.target_percent = max(0.0, min(100.0, float(value)))
